package com.wuxx.quartz.trigger.factory;


import com.wuxx.quartz.model.IntervalTimingMode;
import com.wuxx.quartz.model.TimingModel;
import com.wuxx.quartz.model.TriggerType;
import com.wuxx.quartz.trigger.ITriggerFactory;
import org.nutz.ioc.loader.annotation.IocBean;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;

/**
 * 固定间隔触发器
 * @date 2022/06/08 10:19
 * @author wuxx
 */
@IocBean
public class IntervalTrigger implements ITriggerFactory {
    @Override
    public boolean check(TriggerType triggerType) {
        return triggerType == TriggerType.INTERVAL_MINUTE || triggerType == TriggerType.INTERVAL_SECOND || triggerType == TriggerType.INTERVAL_MILLISECOND||triggerType == TriggerType.INTERVAL_HOUR;
    }

    @Override
    public Trigger build(TimingModel timingModel) {
        if (!(timingModel instanceof IntervalTimingMode)){
            throw new RuntimeException("构建类型为INTERVAL定时必须传入IntervalTimingMode.class的实现类");
        }
        //创建触发器
        IntervalTimingMode intervalTimingMode = (IntervalTimingMode)timingModel;
        SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
        Long interval = intervalTimingMode.getInterval();
        Integer repeatCount = intervalTimingMode.getRepeatCount();
        switch (timingModel.getType()){
            case INTERVAL_MINUTE:
                simpleScheduleBuilder.withIntervalInMinutes(Math.toIntExact(interval));
                break;
            case INTERVAL_HOUR:
                simpleScheduleBuilder.withIntervalInHours(Math.toIntExact(interval));
                break;
            case INTERVAL_SECOND:
                simpleScheduleBuilder.withIntervalInSeconds(Math.toIntExact(interval));
                break;
            case INTERVAL_MILLISECOND:
                simpleScheduleBuilder.withIntervalInMilliseconds(interval);
                break;
        }
        if (repeatCount==null){
            // 无限重复
            simpleScheduleBuilder.repeatForever();
        }else {
            simpleScheduleBuilder.withRepeatCount(repeatCount);
        }
        return TriggerBuilder.newTrigger().withIdentity(timingModel.getTaskName(),timingModel.getGroupName())
                .withSchedule(simpleScheduleBuilder).build();
    }
}
